package org.easy.eao.executer;

import java.lang.reflect.Method;
import java.util.List;

import org.easy.eao.Action;

public class ChainExecuter implements Executer {
	
	/**
	 * 从Action数据创建链式执行器实例
	 * @param actions
	 * @return
	 */
	public static Executer valueOf(List<Action<?>> actions) {
		ChainExecuter result = null;
		for (int i = actions.size() - 1; i >= 0; i--) {
			ChainExecuter current = new ChainExecuter(actions.get(i), result);
			result = current;
		}
		return result;
	}

	private Action<?> action;
	private ChainExecuter next;

	public ChainExecuter(Action<?> action, ChainExecuter next) {
		this.action = action;
		this.next = next;
	}

	@Override
	public Object execute(Method method, Object[] parameters) {
		if (next != null)
			return next.execute(method, executeAction(method, parameters));
		return action.execute(parameters);
	}
	
	private Object[] executeAction(Method method, Object[] parameters) {
		Object result = action.execute(parameters);
		if (result == null)
			return new Object[]{};
		Class<?> clz = result.getClass();
		if (clz.isArray())
			return (Object[]) result;
		else
			return new Object[]{result};
	}

}
